<?php
/**
 * Created by JetBrains PhpStorm.
 * User: valera
 * Date: 8/19/11
 * Time: 11:19 PM
 * To change this template use File | Settings | File Templates.
 */
 
class ZendX_Cache_Manager {
    protected $_block = 100;
    protected $_name = NULL;
    protected $_id = 'id';
    protected $_time_life = 21600;
    private $__data = array();
    private $__cache = NULL;

    public function __construct($name = NULL, $block = NULL) {
        $this->__cache = Zend_Registry::get('Zend_Cache');
        if(NULL !== $block) {
            $this->_block = (int) $block;
        }

        if(NULL !== $name) {
            $this->_name = $name;
        }
    }

    protected function _getCacheKey($block) {
        return "applicationCacheItems{$this->_name}$block";
    }

    protected function _getBlock($id) {
        if($id < 1) return 0;
        return ceil($id/$this->_block)-1;
    }

    protected function _initBlock($block) {
        if(empty($this->__data[$block])) {
            if(FALSE === ($this->__data[$block] = $this->__cache->load($this->_getCacheKey($block)))) {
                $this->rebuild();
                return;
            }
            $this->__data[$block] = (array) json_decode($this->__data[$block]);
        }
    }

    public function rebuild() {
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $data = $db->query("SELECT * FROM {$this->_name};")->fetchAll();

        $size = sizeof($data);
        $blocks = ceil($size / $this->_block);

        for($i = 1; $i <= $size; $i++) {
            $this->__data[$this->_getBlock($i)]['k'.$data[$i-1][$this->_id]] = $data[$i-1];
        }
        for($i = 0; $i < $blocks; $i++) {
            $this->__cache->save(json_encode($this->__data[$i]), $this->_getCacheKey($i), array(), $this->_time_life);
        }
    }
    public function getItems($ids) {
        if(empty($ids)) return array();
        if(is_array($ids)) {
            $result = array();
            foreach($ids as $id) {
                if($id > 0) {
                    $this->_initBlock($block = $this->_getBlock($id));
                    $result[$id] = (array) $this->__data[$block]["k$id"];
                }
            }
            return $result;
        } else {
            $id = (int) $ids;
            $this->_initBlock($block = $this->_getBlock($id));
            return (array) $this->__data[$block]["k$id"];
        }
    }
}